Extension Methods in C#

Another good feature of C # 3.0 is the extension extension. They allow to expand an existing type with new functionality, without compiling the sub-category or re-compiling the old type. For example, you can know whether there was a fixed string number or not always have to define a function and then call it every time, and once you complete those types of tasks , You will put them together in a utility class, such as:


public class MyUtils
{
    public static bool IsNumeric(string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

Now you could check a string by executing a line of code like this:


string test = "4";
if (MyUtils.IsNumeric(test))
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");

However, with extension methods, you can actually extend this string square directly. You define such a stable class, with a set of static methods that will be the library of your extension methods. Here's an example:


public static class MyExtensionMethods
{
    public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

The only thing that distinguishes it from any other static method is the keyword "this" in the parameter section of the method. It tells the compiler that this is an extension method for string class, and it really requires you to create an extension extension. Now, you can call the IsNumeric () method directly on the string, such as:


string test = "4";
if (test.IsNumeric())
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");